<template>
  <view class="container">
    <!-- 订单状态 -->
    <view class="status-section">
      <view class="status-info">
        <text class="status-text" :class="getStatusClass(order.status)">{{ order.statusText }}</text>
        <text class="status-desc">商家进度：{{ order.merchantProcessText }}</text>
        <text class="status-desc">配送进度：{{ order.deliveryProcessText }}</text>
      </view>
    </view>

    <!-- 订单信息 -->
    <view class="order-info">
      <view class="info-item">
        <text class="info-label">订单编号：</text>
        <text class="info-value">{{ order.id }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">下单时间：</text>
        <text class="info-value">{{ order.createTime }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">预约送达时间：</text>
        <text class="info-value">{{ getDeliveryTimeText(order.deliveryTimeType, order.scheduleTime) }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">订单金额：</text>
        <text class="info-value">¥{{ order.totalPrice }}</text>
      </view>
      <view class="info-item" v-if="order.deliveryFee > 0">
        <text class="info-label">配送费：</text>
        <text class="info-value">¥{{ order.deliveryFee }}</text>
      </view>
      <view class="info-item" v-if="order.totalPackagingFee > 0">
        <text class="info-label">打包费：</text>
        <text class="info-value">¥{{ order.totalPackagingFee }}</text>
      </view>
      <view class="info-item" v-if="order.discount > 0">
        <text class="info-label">优惠金额：</text>
        <text class="info-value">¥{{ order.discount }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">实付金额：</text>
        <text class="info-value">¥{{ order.actualPay }}</text>
      </view>
      <view class="info-item">
        <text class="info-label">配送类型：</text>
        <text class="info-value">{{ getDeliveryTypeText(order.deliveryType) }}</text>
      </view>
      <view class="info-item" v-if="order.deliveryAddress">
        <text class="info-label">配送地址：</text>
        <text class="info-value">{{ order.deliveryAddress }}</text>
      </view>
      <view class="info-item" v-if="order.remark">
        <text class="info-label">备注：</text>
        <text class="info-value">{{ order.remark }}</text>
      </view>
      <view class="info-item" v-if="order.receiverName">
        <text class="info-label">收货人：</text>
        <text class="info-value">{{ order.receiverName }}</text>
      </view>
      <view class="info-item" v-if="order.receiverPhone">
        <text class="info-label">联系电话：</text>
        <text class="info-value">{{ order.receiverPhone }}</text>
      </view>
    </view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <view class="section-title">商品信息</view>
      <view class="goods-item" v-for="(item, index) in order.goods" :key="index">
        <image class="goods-image" :src="item.image" mode="aspectFill"></image>
        <view class="goods-detail">
          <view class="goods-name-info">
            <text class="goods-name">{{ item.name }}</text>
            <text class="goods-spec" v-if="item.specifications">{{ formatSpecifications(item.specifications) }}</text>
          </view>
          <view class="goods-price-info">
            <text class="goods-quantity">x{{ item.quantity }}</text>
            <text class="goods-price">¥{{ item.price }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 操作按钮区域 -->
    <view class="action-section">
      <!-- 联系按钮组 -->
      <view v-if="order.customerPhone || order.merchantPhone" class="contact-buttons">
        <view class="contact-row">
          <button v-if="order.customerPhone" class="contact-btn customer-btn" @click="handleContactCustomer">
            <text class="btn-text">联系顾客</text>
          </button>
          <button v-if="order.merchantPhone" class="contact-btn merchant-btn" @click="handleContactMerchant">
            <text class="btn-text">联系商家</text>
          </button>
        </view>
      </view>
      
      <!-- 主要操作按钮 -->
      <view class="main-action">
        <button v-if="order.deliveryProcess===0" class="primary-btn grab-btn" @click="handleGrabOrder(order.id)">
          <view class="primary-btn-content">
            <text class="primary-btn-icon">⚡</text>
            <text class="primary-btn-text">立即抢单</text>
            <text class="primary-btn-desc">快人一步</text>
          </view>
        </button>
        <button v-if="order.deliveryProcess===1" class="primary-btn confirm-btn" @click="handleConfirmPickup(order.id)">
          <view class="primary-btn-content">
            <text class="primary-btn-icon">📦</text>
            <text class="primary-btn-text">确认取货</text>
            <text class="primary-btn-desc">已到达商家</text>
          </view>
        </button>
        <button v-if="order.deliveryProcess===2" class="primary-btn complete-btn" @click="handleCompleteOrder(order.id)">
          <view class="primary-btn-content">
            <text class="primary-btn-icon">✅</text>
            <text class="primary-btn-text">确认送达</text>
            <text class="primary-btn-desc">完成配送</text>
          </view>
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue';
import { onLoad } from '@dcloudio/uni-app';
import { getOrderDetail, grabOrder, confirmPickup, completeOrder } from '@/api/order';
import { useUserStore } from '@/store/user';

const order = ref({});
const userStore = useUserStore();

const formatSpecifications = (specsStr) => {
  try {
    const specs = JSON.parse(specsStr);
    if (!Array.isArray(specs)) return specsStr;
    return specs.map(spec => spec.value).join(',');
  } catch (e) {
    return specsStr;
  }
};


const getStatusClass = (status) => {
  const statusClassMap = {
    2: 'status-pending',
    3: 'status-doing',
    4: 'status-done'
  };
  return statusClassMap[status] || '';
};


const getDeliveryTypeText = (type) => {
  const typeMap = {
    1: '外卖',
    2: '堂食',
    3: '自取'
  };
  return typeMap[type] || '未知';
};

const getDeliveryTimeText = (deliveryTimeType, scheduleTime) => {
  if (deliveryTimeType === 1) {
    return '尽快送达';
  } else {
    return scheduleTime || '未设置';
  }
};

const handleContactCustomer = () => {
  if (order.value.customerPhone) {
    uni.makePhoneCall({ phoneNumber: order.value.customerPhone });
  }
};

const handleContactMerchant = () => {
  if (order.value.merchantPhone) {
    uni.makePhoneCall({ phoneNumber: order.value.merchantPhone });
  }
};

onLoad(async (options) => {
  if (options && options.id) {
    await loadOrderDetail(options.id);
  }
});

const handleGrabOrder = async (orderId) => {
  try {
    const deliveryId = userStore.deliveryId;
    await grabOrder({ orderId, deliveryId });
    uni.showToast({ title: '抢单成功', icon: 'success' });
    // Optionally refresh order data after successful operation
    await loadOrderDetail(orderId);
  } catch (e) {
    console.error('抢单失败:', e);
    uni.showToast({ title: e.message || '抢单失败', icon: 'none' });
  }
};

const handleConfirmPickup = async (orderId) => {
  try {
    await confirmPickup({ orderId });
    uni.showToast({ title: '确认取货成功', icon: 'success' });
    // Optionally refresh order data after successful operation
    await loadOrderDetail(orderId);
  } catch (e) {
    console.error('确认取货失败:', e);
    uni.showToast({ title: e.message || '确认取货失败', icon: 'none' });
  }
};

const handleCompleteOrder = async (orderId) => {
  try {
    await completeOrder({ orderId });
    uni.showToast({ title: '确认送达成功', icon: 'success' });
    // Optionally refresh order data after successful operation
    await loadOrderDetail(orderId);
  } catch (e) {
    console.error('确认送达失败:', e);
    uni.showToast({ title: e.message || '确认送达失败', icon: 'none' });
  }
};

// Helper function to reload order detail after action
const loadOrderDetail = async (orderId) => {
  try {
    const res = await getOrderDetail(orderId);
    order.value = res.data || {};
  } catch (error) {
    console.error('重新加载订单详情失败:', error);
  }
};

</script>

<style lang="scss" scoped>
.container {
  padding: 32rpx;
  background: $bg-primary;
  min-height: 100vh;
}

.status-section {
  @include card-style;
  padding: 40rpx;
  margin-bottom: 32rpx;
  background: $bg-gradient;
  color: #ffffff;
  
  .status-info {
    text-align: center;
  }
}
.status-info {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.status-text {
  font-size: 40rpx;
  font-weight: 700;
  margin-bottom: 20rpx;
  color: #ffffff;
  text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.status-desc {
  font-size: 30rpx;
  color: rgba(255, 255, 255, 0.9);
  margin-bottom: 12rpx;
  line-height: 1.5;
}
.order-info {
  @include card-style;
  padding: 40rpx;
  margin-bottom: 32rpx;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 32rpx;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid $border-light;
  
  &:last-child {
    margin-bottom: 0;
    padding-bottom: 0;
    border-bottom: none;
  }
}

.info-label {
  font-size: 30rpx;
  color: $text-secondary;
  font-weight: 500;
}

.info-value {
  font-size: 30rpx;
  color: $text-primary;
  font-weight: 600;
}
.goods-list {
  @include card-style;
  padding: 40rpx;
  margin-bottom: 32rpx;
}

.section-title {
  font-size: 36rpx;
  font-weight: 700;
  margin-bottom: 32rpx;
  color: $text-primary;
  position: relative;
  padding-left: 20rpx;
  
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 8rpx;
    height: 32rpx;
    background: $bg-gradient;
    border-radius: 4rpx;
  }
}
.goods-item {
  display: flex;
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 2rpx solid #f5f5f5;
}
.goods-image {
  width: 120rpx;
  height: 90rpx;
  border-radius: 16rpx;
  margin-right: 20rpx;
  flex-shrink: 0;
}
.goods-detail {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
.goods-name-info {
  display: flex;
  align-items: center;
  margin-bottom: 8rpx;
}
.goods-name {
  font-size: 28rpx;
  font-weight: 500;
  margin-right: 12rpx;
}
.goods-spec {
  font-size: 24rpx;
  color: #888;
}
.goods-price-info {
  display: flex;
  align-items: center;
}
.goods-quantity {
  font-size: 24rpx;
  color: #888;
  margin-right: 16rpx;
}
.goods-price {
  font-size: 28rpx;
  color: #333;
  font-weight: 600;
}
// 操作按钮区域
.action-section {
  margin-top: 48rpx;
  padding: 0 32rpx 40rpx;
}

// 联系按钮组
.contact-buttons {
  margin-bottom: 24rpx;
}

.contact-row {
  display: flex;
  gap: 16rpx;
  justify-content: center;
}

.contact-btn {
  background: #ffffff;
  border: 2rpx solid #e5e7eb;
  border-radius: 16rpx;
  padding: 16rpx 24rpx;
  min-width: 120rpx;
  height: 64rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:active {
    transform: scale(0.96);
    background: #f9fafb;
  }
  
  .btn-text {
    font-size: 26rpx;
    font-weight: 500;
    color: $text-primary;
  }
}

.customer-btn {
  border-color: #10b981;
  
  .btn-icon {
    color: #10b981;
  }
  
  &:active {
    background: rgba(16, 185, 129, 0.05);
    border-color: #059669;
  }
}

.merchant-btn {
  border-color: #f59e0b;
  
  .btn-icon {
    color: #f59e0b;
  }
  
  &:active {
    background: rgba(245, 158, 11, 0.05);
    border-color: #d97706;
  }
}

// 主要操作按钮
.main-action {
  display: flex;
  justify-content: center;
}

.primary-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 28rpx;
  padding: 0;
  width: 100%;
  max-width: 400rpx;
  height: 120rpx;
  box-shadow: 0 12rpx 32rpx rgba(102, 126, 234, 0.3);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.8s ease;
  }
  
  &:active {
    transform: translateY(4rpx) scale(0.98);
    box-shadow: 0 6rpx 16rpx rgba(102, 126, 234, 0.4);
    
    &::before {
      left: 100%;
    }
  }
  
  .primary-btn-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    color: #ffffff;
  }
  
  .primary-btn-icon {
    font-size: 36rpx;
    margin-bottom: 8rpx;
    filter: drop-shadow(0 2rpx 4rpx rgba(0, 0, 0, 0.2));
  }
  
  .primary-btn-text {
    font-size: 32rpx;
    font-weight: 700;
    margin-bottom: 4rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.2);
  }
  
  .primary-btn-desc {
    font-size: 22rpx;
    opacity: 0.9;
    font-weight: 400;
  }
}

.grab-btn {
  background: linear-gradient(135deg, #ff6b6b 0%, #ee5a24 100%);
  box-shadow: 0 12rpx 32rpx rgba(255, 107, 107, 0.3);
  
  &:active {
    box-shadow: 0 6rpx 16rpx rgba(255, 107, 107, 0.4);
  }
}

.confirm-btn {
  background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
  box-shadow: 0 12rpx 32rpx rgba(78, 205, 196, 0.3);
  
  &:active {
    box-shadow: 0 6rpx 16rpx rgba(78, 205, 196, 0.4);
  }
}

.complete-btn {
  background: linear-gradient(135deg, #a8e6cf 0%, #7fcdcd 100%);
  box-shadow: 0 12rpx 32rpx rgba(168, 230, 207, 0.3);
  
  &:active {
    box-shadow: 0 6rpx 16rpx rgba(168, 230, 207, 0.4);
  }
}
</style>